package com.linsen.core.mybatisplus.handler;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.linsen.core.common.context.TenantContextHolder;
import com.linsen.core.mybatisplus.props.LinsenMyBatisPlusProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.schema.Column;

import java.util.List;

/**
 * 多租户插件
 *
 * @author zhaoyong
 * @date 2023/3/11
 */
@Slf4j
@RequiredArgsConstructor
public class LinsenTenantLineHandler implements TenantLineHandler {
    private final LinsenMyBatisPlusProperties myBatisPlusProperties;

    @Override
    public Expression getTenantId() {
        String tenantId = TenantContextHolder.getTenantId();
        return StrUtil.isBlank(tenantId) ? new NullValue() : new StringValue(tenantId);
    }

    @Override
    public String getTenantIdColumn() {
        return TenantLineHandler.super.getTenantIdColumn();
    }

    @Override
    public boolean ignoreTable(String tableName) {
        return this.myBatisPlusProperties.getTenantLineHandlerIgnoreTables().contains(tableName);
    }

    @Override
    public boolean ignoreInsert(List<Column> columns, String tenantIdColumn) {
        return TenantLineHandler.super.ignoreInsert(columns, tenantIdColumn);
    }
}
